/**
 * Copyright (c) 2011-2014, James Zhan 詹波 (jfinal@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.tianqi.config;

import java.util.List;

import com.jfinal.kit.PropKit;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.jfinal.MsgControllerAdapter;
import com.jfinal.weixin.sdk.msg.in.InImageMsg;
import com.jfinal.weixin.sdk.msg.in.InLinkMsg;
import com.jfinal.weixin.sdk.msg.in.InLocationMsg;
import com.jfinal.weixin.sdk.msg.in.InShortVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InTextMsg;
import com.jfinal.weixin.sdk.msg.in.InVideoMsg;
import com.jfinal.weixin.sdk.msg.in.InVoiceMsg;
import com.jfinal.weixin.sdk.msg.in.event.InCustomEvent;
import com.jfinal.weixin.sdk.msg.in.event.InFollowEvent;
import com.jfinal.weixin.sdk.msg.in.event.InLocationEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMassEvent;
import com.jfinal.weixin.sdk.msg.in.event.InMenuEvent;
import com.jfinal.weixin.sdk.msg.in.event.InTemplateMsgEvent;
import com.jfinal.weixin.sdk.msg.in.speech_recognition.InSpeechRecognitionResults;
import com.jfinal.weixin.sdk.msg.out.OutCustomMsg;
import com.jfinal.weixin.sdk.msg.out.OutNewsMsg;
import com.jfinal.weixin.sdk.msg.out.OutTextMsg;
import com.tianqi.rms.model.Keyword;
import com.tianqi.rms.model.Relation;
import com.tianqi.rms.model.TRepnews;
import com.tianqi.rms.model.TReptext;
import com.tianqi.rms.model.TWeixinNo;

/**
 * 将此 DemoController 在YourJFinalConfig 中注册路由，
 * 并设置好weixin开发者中心的 URL 与 token ，使 URL 指向该
 * DemoController 继承自父类 WeixinController 的 index
 * 方法即可直接运行看效果，在此基础之上修改相关的方法即可进行实际项目开发
 */
public class WeixinMsgController extends MsgControllerAdapter {

    static Log logger = Log.getLog(WeixinMsgController.class);
	public static String appId;
    
    public ApiConfig getApiConfig() {
		//改成
    	appId = getPara();
		if (StrKit.isBlank(appId)) {
			appId = "wxf1dced1caa5991d8";
		}
		TWeixinNo wx =TWeixinNo.dao.getWeChatInfoByappId(appId);
		ApiConfig ac = new ApiConfig();
		// 配置微信 API 相关常量
		ac.setToken(wx.getToken());
		ac.setAppId(wx.getAppid());
		ac.setAppSecret(wx.getAeskey());
		/**
		 * 是否对消息进行加密，对应于微信平台的消息加解密方式： 1：true进行加密且必须配置 encodingAesKey
		 * 2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey","setting it in config file"));
		return ac;
	}
    /**
	 * 关键字回复
	 */
	protected void processInTextMsg(InTextMsg inTextMsg){
		try {
			String msgContent = inTextMsg.getContent().trim();
			//String appId = PropKit.get("appId");
			TWeixinNo wx= TWeixinNo.dao.readWxByAppId(appId);
			List<Keyword> keywords =Keyword.dao.readKeyWordByWechatId(wx.getId(), msgContent);
			if(keywords==null) {
				renderText("");
				return;
			}
			OutNewsMsg outNewsMsg = new OutNewsMsg(inTextMsg);
			for (Keyword keyword : keywords) {
				if(keyword.getType()==1) {
					List<Relation>relations=Relation.dao.relationBykwId(keyword.getId());
					if(relations!=null) {
						for (Relation relation : relations) {
							int mid=relation.getMaterialId();
							TReptext rt=TReptext.dao.readTextByKwId(mid);
							OutTextMsg outMsg = new OutTextMsg(inTextMsg);
							outMsg.setContent(rt.getContent());
							render(outMsg);
						}
						return ;
					}
				}else if (keyword.getType()==2) {
					List<TRepnews>news=TRepnews.dao.readNews(keyword.getId());	
					for (TRepnews rnew : news) {
						outNewsMsg.addNews(rnew.getTitle(),rnew.getDecription(),rnew.getPicUrl(),rnew.getUrl());
					}
				}
			}
			render(outNewsMsg);
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("文本回复异常："+e);
			renderText("");
		}
	}

    @Override
    protected void processInVoiceMsg(InVoiceMsg inVoiceMsg) {
        OutTextMsg outMsg = new OutTextMsg(inVoiceMsg);
        outMsg.setContent("语音消息~");
        renderNull();
    }

    @Override
    protected void processInVideoMsg(InVideoMsg inVideoMsg) {
        OutTextMsg outMsg = new OutTextMsg(inVideoMsg);
        outMsg.setContent("接收视频消息~");
        renderNull();
    }

    @Override
    protected void processInShortVideoMsg(InShortVideoMsg inShortVideoMsg) {
        OutTextMsg outMsg = new OutTextMsg(inShortVideoMsg);
        outMsg.setContent("小视频消息~");
        renderNull();
    }

    @Override
    protected void processInLocationMsg(InLocationMsg inLocationMsg) {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inLocationMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInLinkMsg(InLinkMsg inLinkMsg)
    {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inLinkMsg);
        render(outCustomMsg);
    }

    @Override
    protected void processInCustomEvent(InCustomEvent inCustomEvent)
    {
        logger.debug("测试方法：processInCustomEvent()");
        renderNull();
    }

    protected void processInImageMsg(InImageMsg inImageMsg)
    {
        //转发给多客服PC客户端
        OutCustomMsg outCustomMsg = new OutCustomMsg(inImageMsg);
        render(outCustomMsg);
    }

    /**
     * 实现父类抽方法，处理关注/取消关注消息
     */
    protected void processInFollowEvent(InFollowEvent inFollowEvent)
    {
        if (InFollowEvent.EVENT_INFOLLOW_SUBSCRIBE.equals(inFollowEvent.getEvent()))
        {
            logger.info("关注：" + inFollowEvent.getFromUserName());
            //String appId = PropKit.get("appId");
			TWeixinNo wx= TWeixinNo.dao.readWxByAppId(appId);
			List<Keyword> keywords =Keyword.dao.readKeyWordByWechatId(wx.getId(), "SUBSCRIBE");
			System.out.println(keywords+"====keyword==="+wx);
			if(keywords==null) {
				renderText("");
				return;
			}
			OutNewsMsg outNewsMsg = new OutNewsMsg(inFollowEvent);
			for (Keyword keyword : keywords) {
				if(keyword.getType()==1) {
					List<Relation>relations=Relation.dao.relationBykwId(keyword.getId());
					if(relations!=null) {
						for (Relation relation : relations) {
							int mid=relation.getMaterialId();
							TReptext rt=TReptext.dao.readTextByKwId(mid);
							OutTextMsg outMsg = new OutTextMsg(inFollowEvent);
							outMsg.setContent(rt.getContent());
							render(outMsg);
						}
						return ;
					}
				}else if (keyword.getType()==2) {
					List<TRepnews>news=TRepnews.dao.readNews(keyword.getId());	
					System.out.println(news +"=====news");
					for (TRepnews rnew : news) {
						outNewsMsg.addNews(rnew.getTitle(),rnew.getDecription(),rnew.getPicUrl(),rnew.getUrl());
					}
				}
			}
			render(outNewsMsg);
            
        }
        // 如果为取消关注事件，将无法接收到传回的信息
        if (InFollowEvent.EVENT_INFOLLOW_UNSUBSCRIBE.equals(inFollowEvent.getEvent()))
        {
            logger.info("取消关注：" + inFollowEvent.getFromUserName());
        }
    }

    @Override
    protected void processInLocationEvent(InLocationEvent inLocationEvent)
    {
        logger.debug("发送地理位置事件：" + inLocationEvent.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inLocationEvent);
        outMsg.setContent("地理位置是：" + inLocationEvent.getLatitude());
        render(outMsg);
    }

    @Override
    protected void processInMassEvent(InMassEvent inMassEvent)
    {
        logger.debug("测试方法：processInMassEvent()");
        renderNull();
    }
    /**
     * 实现父类抽方法，处理自定义菜单事件
     */
    protected void processInMenuEvent(InMenuEvent inMenuEvent)
    {
    	try {
			String key = inMenuEvent.getEventKey();
			//String appId = PropKit.get("appId");
			TWeixinNo wx= TWeixinNo.dao.readWxByAppId(appId);
			List<Keyword> keywords =Keyword.dao.readKeyWordByWechatId(wx.getId(), key);
			if(keywords==null) {
				renderText("");
				return;
			}
			OutNewsMsg outNewsMsg = new OutNewsMsg(inMenuEvent);
			for (Keyword keyword : keywords) {
				if(keyword.getType()==1) {
					List<Relation> relations=Relation.dao.relationBykwId(keyword.getId());
					if(relations!=null) {
						Relation relation=relations.get(0);
						int mid=relation.getMaterialId();
						TReptext rt=TReptext.dao.readTextByKwId(mid);
						OutTextMsg outMsg = new OutTextMsg(inMenuEvent);
						outMsg.setContent(rt.getContent());
						render(outMsg);
						return ;
					}
				}else if (keyword.getType()==2) {
					List<TRepnews>news=TRepnews.dao.readNews(keyword.getId());	
					for (TRepnews rnew : news) {
						outNewsMsg.addNews(rnew.getTitle(),rnew.getDecription(),rnew.getPicUrl(),rnew.getUrl());
					}
				}
			}
			render(outNewsMsg);
		} catch (Exception e) {
			e.printStackTrace();
			renderText("");
		}
    }
    
    
    public void date() {
    	//String appId = PropKit.get("appId");
		TWeixinNo wx= TWeixinNo.dao.readWxByAppId(appId);
		List<Keyword> keywords =Keyword.dao.readKeyWordByWechatId(wx.getId(), "测试");
		System.out.println(keywords);
    }

    @Override
    protected void processInSpeechRecognitionResults(InSpeechRecognitionResults inSpeechRecognitionResults)
    {
        logger.debug("语音识别事件：" + inSpeechRecognitionResults.getFromUserName());
        OutTextMsg outMsg = new OutTextMsg(inSpeechRecognitionResults);
        outMsg.setContent("语音识别内容是：" + inSpeechRecognitionResults.getRecognition());
        render(outMsg);
    }

    @Override
    protected void processInTemplateMsgEvent(InTemplateMsgEvent inTemplateMsgEvent)
    {
        logger.debug("测试方法：processInTemplateMsgEvent()");
        renderNull();
    }
}






